<template>
  <Header :class="getHeaderClass">
    <!-- left start -->
    <div :class="`${prefixCls}-left`">
      <!-- logo -->
      <AppLogo
        v-if="getShowHeaderLogo || getIsMobile"
        :class="`${prefixCls}-logo`"
        :theme="getHeaderTheme"
        :style="getLogoWidth"
      />
      <LayoutTrigger
        v-if="
          (getShowContent && getShowHeaderTrigger && !getSplit && !getIsMixSidebar) || getIsMobile
        "
        :theme="getHeaderTheme"
        :sider="false"
      />
      <LayoutBreadcrumb v-if="getShowContent && getShowBread" :theme="getHeaderTheme" />
    </div>
    <!-- left end -->

    <!-- menu start -->
    <div :class="`${prefixCls}-menu`" v-if="getShowTopMenu && !getIsMobile">
      <LayoutMenu
        :isHorizontal="true"
        :theme="getHeaderTheme"
        :splitType="getSplitType"
        :menuMode="getMenuMode"
      />
    </div>
    <!-- menu-end -->

    <!-- action  -->
    <div :class="`${prefixCls}-action`">
      <AppSearch :class="`${prefixCls}-action__item `" v-if="getShowSearch" />

      <!--      <Notify v-if="getShowNotice" :class="`${prefixCls}-action__item notify-item`" />-->
      <!--      <Notice :class="`${prefixCls}-action__item notify-item`" />-->
      <a-badge
        :count="data.filter((s) => s.status == 0).length"
        dot
        :numberStyle="{ marginTop: '12px', marginRight: '4px' }"
      >
        <a-tooltip>
          <template #title>消息通知</template>
          <BellOutlined :class="`${prefixCls}-action__item `" @click="clickNotice" />
        </a-tooltip>
      </a-badge>

      <FullScreen v-if="getShowFullScreen" :class="`${prefixCls}-action__item fullscreen-item`" />
      <a-tooltip>
        <template #title>修改密码</template>
        <UnlockOutlined :class="`${prefixCls}-action__item `" @click="clickUpdatePwd" />
      </a-tooltip>

      <!-- <AppLocalePicker
        v-if="getShowLocalePicker"
        :reload="true"
        :showText="false"
        :class="`${prefixCls}-action__item`"
      /> -->

      <UserDropDown :theme="getHeaderTheme" />

      <!-- <SettingDrawer v-if="getShowSetting" :class="`${prefixCls}-action__item`" /> -->
    </div>
    <a-modal v-model:visible="open" title="消息通知" width="960px" body-style="padding:0 24px">
      <template #footer>
        <a-button key="submit" type="primary" @click="readAll" style="align-content: center"
          >全部已读</a-button
        >
      </template>
      <a-table :columns="columns" :data-source="data" size="small">
        <template #bodyCell="{ column, record }">
          <!--          <template v-if="column.key === 'type'">-->
          <!--            <a-tag :color="record.color">{{ record.type }}</a-tag>-->
          <!--          </template>-->
          <template v-if="column.key === 'status'">
            <a-tag color="blue" v-if="record.status === 1">已读</a-tag>
            <a-tag color="red" v-else>未读</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button
              v-if="record.status == 0"
              class="button-interval"
              type="link"
              size="small"
              @click="read(record)"
            >
              标为已读
            </a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
    <audio ref="audio">
      <source src="../../../assets/audio/audio.mp3" type="audio/mpeg" />
      <!--      <source :src="audioPath1" type="audio/mpeg" />-->
    </audio>
    <a-modal
      v-model:visible="openPwd"
      title="修改密码"
      :body-style="{ padding: '16px 24px' }"
      @ok="submitPwd"
    >
      <div>
        <div
          >　新密码：<a-input-password
            style="width: calc(100% - 80px)"
            v-model:value="pwd1"
            placeholder="输入新密码"
        /></div>
        <div style="margin-top: 16px"
          >确认密码：<a-input-password
            style="width: calc(100% - 80px)"
            v-model:value="pwd2"
            placeholder="再次输入新密码"
        /></div>
      </div>
    </a-modal>
  </Header>
</template>
<script lang="ts">
  import { defineComponent, unref, computed, onMounted, h, ref } from 'vue'

  import { propTypes } from '/@/utils/propTypes'

  import { Layout, notification, Button, message } from 'ant-design-vue'
  import { BellOutlined, UnlockOutlined } from '@ant-design/icons-vue'
  import { AppLogo } from '/@/components/Application'
  import LayoutMenu from '../menu/index.vue'
  import LayoutTrigger from '../trigger/index.vue'

  import { AppSearch } from '/@/components/Application'

  import { useHeaderSetting } from '/@/hooks/setting/useHeaderSetting'
  import { useMenuSetting } from '/@/hooks/setting/useMenuSetting'
  import { useRootSetting } from '/@/hooks/setting/useRootSetting'

  import { MenuModeEnum, MenuSplitTyeEnum } from '/@/enums/menuEnum'
  import { SettingButtonPositionEnum } from '/@/enums/appEnum'
  import { AppLocalePicker } from '/@/components/Application'

  import { UserDropDown, LayoutBreadcrumb, FullScreen, Notify, Notice } from './components'
  // import Notice from './components/notice/index.vue'
  import { useAppInject } from '/@/hooks/web/useAppInject'
  import { useDesign } from '/@/hooks/web/useDesign'

  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent'
  import { useLocale } from '/@/locales/useLocale'

  import { useUserStore } from '/@/store/modules/user'
  // import { PropType } from 'vue/dist/vue'
  const userStore = useUserStore()
  const userInfo = userStore.getUserInfo

  import { listNotice, readNotice, readAllNotice } from '/@/api/notice'
  import { updatePassword } from '/@/api/sys/user'
  import { NoticeVO } from '/@/api/notice/model/noticeModel'
  // import { Notice } from '/@/layouts/default/header/components'

  export default defineComponent({
    name: 'LayoutHeader',
    components: {
      Header: Layout.Header,
      AppLogo,
      LayoutTrigger,
      LayoutBreadcrumb,
      LayoutMenu,
      UserDropDown,
      AppLocalePicker,
      FullScreen,
      Notify,
      Notice,
      AppSearch,
      BellOutlined,
      UnlockOutlined,
      SettingDrawer: createAsyncComponent(() => import('/@/layouts/default/setting/index.vue'), {
        loading: true,
      }),
      listNotice,
      readNotice,
      readAllNotice,
      updatePassword,
    },
    props: {
      fixed: propTypes.bool,
    },
    setup(props) {
      // onMounted(() => {
      //   init(userInfo.userId)
      // })
      const { prefixCls } = useDesign('layout-header')
      const audio = ref(null)
      // const mNotice = ref<InstanceType<typeof Notice> | null>(null)
      const open = ref(false)
      const openPwd = ref(false)
      const pwd1 = ref('')
      const pwd2 = ref('')

      const data = ref<NoticeVO[]>([])
      const columns = [
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          align: 'center',
          width: 120,
        },
        {
          title: '内容',
          dataIndex: 'content',
          key: 'content',
          align: 'center',
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          align: 'center',
          width: 100,
        },
        {
          title: '时间',
          dataIndex: 'createTime',
          key: 'createTime',
          align: 'center',
          width: 160,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          align: 'center',
          width: 100,
        },
      ]

      const {
        getShowTopMenu,
        getShowHeaderTrigger,
        getSplit,
        getIsMixMode,
        getMenuWidth,
        getIsMixSidebar,
      } = useMenuSetting()
      const { getUseErrorHandle, getShowSettingButton, getSettingButtonPosition } = useRootSetting()

      const {
        getHeaderTheme,
        getShowFullScreen,
        getShowNotice,
        getShowContent,
        getShowBread,
        getShowHeaderLogo,
        getShowHeader,
        getShowSearch,
      } = useHeaderSetting()

      const { getShowLocalePicker } = useLocale()

      const { getIsMobile } = useAppInject()

      const getHeaderClass = computed(() => {
        const theme = unref(getHeaderTheme)
        return [
          prefixCls,
          {
            [`${prefixCls}--fixed`]: props.fixed,
            [`${prefixCls}--mobile`]: unref(getIsMobile),
            [`${prefixCls}--${theme}`]: theme,
          },
        ]
      })

      const getShowSetting = computed(() => {
        if (!unref(getShowSettingButton)) {
          return false
        }
        const settingButtonPosition = unref(getSettingButtonPosition)

        if (settingButtonPosition === SettingButtonPositionEnum.AUTO) {
          return unref(getShowHeader)
        }
        return settingButtonPosition === SettingButtonPositionEnum.HEADER
      })

      const getLogoWidth = computed(() => {
        if (!unref(getIsMixMode) || unref(getIsMobile)) {
          return {}
        }
        const width = unref(getMenuWidth) < 180 ? 180 : unref(getMenuWidth)
        return { width: `${width}px` }
      })

      const getSplitType = computed(() => {
        return unref(getSplit) ? MenuSplitTyeEnum.TOP : MenuSplitTyeEnum.NONE
      })

      const getMenuMode = computed(() => {
        return unref(getSplit) ? MenuModeEnum.HORIZONTAL : null
      })
      // const listData = ref<NoticeVO[]>([])
      onMounted(() => {
        initWebSocket(userInfo.userId)
        list()
      })
      const list = () => {
        listNotice().then((res) => {
          data.value = res
        })
      }

      const read = async (record) => {
        await readNotice(record.id).then(() => {
          list()
        })
      }

      const readAll = async () => {
        await readAllNotice().then(() => {
          list()
          message.success('操作成功')
          open.value = false
        })
      }

      const clickNotice = () => {
        console.log('click notice')
        list()
        open.value = true
        console.log('click notice2')
      }

      const path = 'ws://121.43.125.179:7410/basic-api/websocket/'
      // const path = 'ws://localhost:8080/websocket/'
      const initWebSocket = (userId) => {
        const ws = new WebSocket(path + userId)
        //监听是否连接成功
        ws.onopen = () => {
          console.log('ws连接状态：', ws.readyState)
          //连接成功则发送一个数据
          ws.send('连接成功')
        }

        //接听服务器发回的信息并处理展示
        ws.onmessage = (data) => {
          console.log('接收到来自服务器的消息：')
          console.log(data)
          console.log(data.data)
          const notice = JSON.parse(data.data)
          const key = `open${Date.now()}`
          audio.value!.click()
          audio.value!.play()
          list()
          notification.open({
            message: notice['type'],
            description: notice['content'],
            btn: () =>
              h(
                Button,
                {
                  type: 'primary',
                  size: 'small',
                  onClick: () => notification.close(key),
                },
                { default: () => '去处理' },
              ),
            key,
          })
        }

        //监听连接关闭事件
        ws.onclose = () => {
          //监听整个过程中websocket的状态
          console.log('ws连接状态：' + ws.readyState)
        }

        //监听并处理error事件
        ws.onerror = function (error) {
          console.error('error', error)
        }
      }

      const clickUpdatePwd = () => {
        console.log('clickUpdatePwd')
        openPwd.value = true
      }

      const submitPwd = () => {
        if (pwd1.value === '') {
          message.error('请输入密码')
          return
        }
        if (pwd1.value != pwd2.value) {
          message.error('两次密码不一致')
          return
        }
        updatePassword(pwd1.value).then(() => {
          message.success('密码修改成功')
          openPwd.value = false
        })
      }

      return {
        prefixCls,
        getHeaderClass,
        getShowHeaderLogo,
        getHeaderTheme,
        getShowHeaderTrigger,
        getIsMobile,
        getShowBread,
        getShowContent,
        getSplitType,
        getSplit,
        getMenuMode,
        getShowTopMenu,
        getShowLocalePicker,
        getShowFullScreen,
        getShowNotice,
        getUseErrorHandle,
        getLogoWidth,
        getIsMixSidebar,
        getShowSettingButton,
        getShowSetting,
        getShowSearch,
        audio,
        clickNotice,
        read,
        readAll,
        open,
        openPwd,
        clickUpdatePwd,
        columns,
        data,
        numberStyle: {},
        pwd1,
        pwd2,
        submitPwd,
      }
    },
  })
</script>
<style lang="less">
  @import './index.less';
</style>
